﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using DACU.Player.Enums;
using DACU.VkontakteApi.Base;
using DACU.VkontakteApi.Collections;
using DACU.VkontakteApi.Enums;

namespace DACU.Tools
{
	static class Extensions
	{
		public static string FormatStr(this string str, params object[] args)
		{
			return args != null && args.Length > 0 ? String.Format(str, args) : str;
		}

		public static string ToTrimString(this VKFields fields)
		{
			if(fields == VKFields.All)
			{
				string[] names = Enum.GetNames(typeof(VKFields));
				var sb = new StringBuilder();
				for (int i = 0; i < names.Length; i++)
					sb.AppendFormat("{0},", names[i]);
				sb.Replace("All", "");
				sb.Replace("None", "");
				return sb.ToString().Trim(new[]{','});
			}
			return fields.ToString().Replace(" ", "");
		}

		public static string GetPatterned(this SupportedFormats format)
		{
			if (format == SupportedFormats.None)
				return "";
			if (format == SupportedFormats.All)
			{
				string[] names = Enum.GetNames(typeof(SupportedFormats));
				var sb = new StringBuilder();
				for (int i = 0; i < names.Length; i++)
					sb.AppendFormat("*.{0};", names[i]);
				sb.Replace("All", "");
				sb.Replace("None", "");
				return sb.ToString().Trim(new[] { ';' });
			}
			return "*.{0}".FormatStr(format);
		}

		public static VKFriendsCollection ToFriends(this IEnumerable<VKUserProfile> ienums)
		{
			return new VKFriendsCollection(ienums);
		}

		public static VKFriendsCollection ToFriends(this IOrderedEnumerable<VKUserProfile> ienums)
		{
			return new VKFriendsCollection(ienums);
		}

		public static VKAudioCollection ToAudioCollection(this IEnumerable<VKAudio> ienums)
		{
			return new VKAudioCollection(ienums);
		}

		public static VKAudioCollection ToAudioCollection(this IEnumerable<VKAudio> ienums,DateTime timestamp)
		{
			return new VKAudioCollection(ienums){DownloadTimeStamp = timestamp};
		}

		public static string TryGetString(this Dictionary<string, object> coll, string key)
		{
			if (coll.ContainsKey(key)) return (coll[key] ?? "") is string ? coll[key] as string : coll[key].ToString();
			return "";
		}

		public static int TryGetInt(this Dictionary<string, object> coll, string key)
		{
			if (coll.ContainsKey(key)) return (int) coll[key];
			return -1;
		}

		public static double ToDouble(this string str)
		{
			double d;
			return double.TryParse(str, out d) ? d : double.NaN;
		}

		public static int FindIndex(this ItemCollection collection, Predicate<object> match)
		{
			if (match == null)
				throw new ArgumentNullException("match");
			//Array.BinarySearch(collection, );
			int num = collection.Count;
			for (int i = 0; i < num; i++)
			{
				if (match(collection[i]))
					return i;
			}
			return -1;
		}
	}
}
